//
//  MyWindow.m
//  jRSSReader
//
//  Created by Jodynek on 4/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MyWindow.h"
#import "frmSettingsController.h"

@implementation MyWindow
@synthesize view;

+(void) initialize
{
  // application defaults
  NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];
  [defaultValues setObject:@"" forKey:@"sUserName"];
  [defaultValues setObject:@"" forKey:@"sPassword"];
  [defaultValues setObject:@"300" forKey:@"iShiftDelay"];
  [defaultValues setObject:@"1800" forKey:@"iRefreshDelay"];
  [[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];  
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation 
{
  if (self = [super initWithContentRect:contentRect
                              styleMask:NSBorderlessWindowMask
                                backing:NSBackingStoreBuffered defer:deferCreation]) 
  {
    [self setAcceptsMouseMovedEvents:YES];
    [self setBackgroundColor: [NSColor clearColor]];
    [self setAlphaValue:0.90];
    [self setOpaque:NO];
    [self setExcludedFromWindowsMenu:NO];		
    [self setHasShadow:YES];
    forceDisplay = NO;
    [self setBackgroundColor:[self sizedHUDBackground]];    
    [self addCloseWidget];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(windowDidResize:) 
                                                 name:NSWindowDidResizeNotification 
                                               object:self];    
    [[NSNotificationCenter defaultCenter] addObserver:self
           selector:@selector(handlePrefSaved:)
               name:prefSavedNotification
             object:nil];
    shouldRedoInitials = true;
    // login to google reader
    [self initLogin];
 	}
	return self;
}

- (void)handlePrefSaved:(NSNotification *)note
{
  [self initLogin];
<<<<<<< HEAD
  [self setTimers];
}

- (void) setTimers
{
  // run timer - feeds shifting
  int iShiftDelay = [[frmSettingsController shiftDelay] intValue];
  int iUpdateRSSDelay = [[frmSettingsController refreshDelay] intValue];
  [timer invalidate];
  timer = nil;
  timer = [NSTimer scheduledTimerWithTimeInterval: iShiftDelay
                                           target: self
                                         selector: @selector(onTick:)
                                         userInfo: nil repeats:YES];  
  // update timer - update list of RSS after interval
  [updateRSSTimer invalidate];
  updateRSSTimer = nil;
  updateRSSTimer = [NSTimer scheduledTimerWithTimeInterval: iUpdateRSSDelay
                                                    target: self
                                                  selector: @selector(onRSSUpdateTimer:)
                                                  userInfo: nil repeats:YES];    
=======
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
}

- (void)initLogin
{
  wndSettings = [[frmSettingsController alloc] initWithWindowNibName:@"frmSettings"];      
  NSString *sUserName = [frmSettingsController userName];
  NSString *sPass = [frmSettingsController password];
  if ([sUserName isNotEqualTo:@""])
  {
    // google reader login
    gr = [[GoogleReader alloc] init];
    [gr login:sUserName pass:sPass];  
    [view refreshStories:gr];
  }
}

- (IBAction)mnuSettingsClicked:(id)sender 
{
  [self settingsWindow:sender];
}

- (NSColor *)sizedHUDBackground
{
  float alpha = 0.75;
  float titlebarHeight = 19.0;
  NSImage *bg = [[NSImage alloc] initWithSize:[self frame].size];
  [bg lockFocus];
  
  // Make background path
  NSRect bgRect = NSMakeRect(0, 0, [bg size].width, [bg size].height - titlebarHeight);
  int minX = NSMinX(bgRect);
  int midX = NSMidX(bgRect);
  int maxX = NSMaxX(bgRect);
  int minY = NSMinY(bgRect);
  int midY = NSMidY(bgRect);
  int maxY = NSMaxY(bgRect);
  float radius = 6.0;
  NSBezierPath *bgPath = [NSBezierPath bezierPath];
  
  // Bottom edge and bottom-right curve
  [bgPath moveToPoint:NSMakePoint(midX, minY)];
  [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(maxX, minY) 
                                   toPoint:NSMakePoint(maxX, midY) 
                                    radius:radius];
  
  [bgPath lineToPoint:NSMakePoint(maxX, maxY)];
  [bgPath lineToPoint:NSMakePoint(minX, maxY)];
  
  // Top edge and top-left curve
  [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(minX, maxY) 
                                   toPoint:NSMakePoint(minX, midY) 
                                    radius:radius];
  
  // Left edge and bottom-left curve
  [bgPath appendBezierPathWithArcFromPoint:bgRect.origin 
                                   toPoint:NSMakePoint(midX, minY) 
                                    radius:radius];
  [bgPath closePath];
  
  // Composite background color into bg
  [[NSColor colorWithCalibratedWhite:0.1 alpha:alpha] set];
  [bgPath fill];
  
  // Make titlebar path
  NSRect titlebarRect = NSMakeRect(0, [bg size].height - titlebarHeight, [bg size].width, titlebarHeight);
  minX = NSMinX(titlebarRect);
  midX = NSMidX(titlebarRect);
  maxX = NSMaxX(titlebarRect);
  minY = NSMinY(titlebarRect);
  midY = NSMidY(titlebarRect);
  maxY = NSMaxY(titlebarRect);
  NSBezierPath *titlePath = [NSBezierPath bezierPath];
  
  // Bottom edge and bottom-right curve
  [titlePath moveToPoint:NSMakePoint(minX, minY)];
  [titlePath lineToPoint:NSMakePoint(maxX, minY)];
  
  // Right edge and top-right curve
  [titlePath appendBezierPathWithArcFromPoint:NSMakePoint(maxX, maxY) 
                                      toPoint:NSMakePoint(midX, maxY) 
                                       radius:radius];
  
  // Top edge and top-left curve
  [titlePath appendBezierPathWithArcFromPoint:NSMakePoint(minX, maxY) 
                                      toPoint:NSMakePoint(minX, minY) 
                                       radius:radius];
  
  [titlePath closePath];
  
  // Titlebar
  NSColor *titlebarColor = [NSColor colorWithCalibratedWhite:0.25 alpha:alpha];
  [titlebarColor set];
  [titlePath fill];
  
  // Title
  NSFont *titleFont = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
  NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
  [paraStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
  [paraStyle setAlignment:NSCenterTextAlignment];
  [paraStyle setLineBreakMode:NSLineBreakByTruncatingTail];
  NSMutableDictionary *titleAttrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     titleFont, NSFontAttributeName,
                                     [NSColor whiteColor], NSForegroundColorAttributeName,
                                     [paraStyle copy], NSParagraphStyleAttributeName,
                                     nil];
  
  NSSize titleSize = [[self title] sizeWithAttributes:titleAttrs];
  // We vertically centre the title in the titlbar area, and we also horizontally 
  // inset the title by 19px, to allow for the 3px space from window's edge to close-widget, 
  // plus 13px for the close widget itself, plus another 3px space on the other side of 
  // the widget.
  NSRect titleRect = NSInsetRect(titlebarRect, 19.0, (titlebarRect.size.height - titleSize.height) / 2.0);
  [[self title] drawInRect:titleRect withAttributes:titleAttrs];
  [bg unlockFocus];
  
  return [NSColor colorWithPatternImage:bg];
}

- (void)awakeFromNib
{
  [self addCloseWidget];  
  [self setTimers];
  // show news
  [view refreshStories:gr];
}

// refresh RSS list
- (void)onRSSUpdateTimer:(NSTimer *)timer;
{
  [view refreshStories:gr];
}

// shift news feeds
-(void)onTick:(NSTimer *)timer 
{
  [view shiftFeeds];
}

- (void)windowDidResize:(NSNotification *)aNotification
{
  // move close button
  if ([[[self contentView] subviews] count] > 0)
  {
    NSButton *closeButton = [[[self contentView] subviews] objectAtIndex:0];
    CGRect r;
    r = NSMakeRect(3.0, [self frame].size.height - 16.0, 
                   20.0, 13.0);
    [closeButton setFrame:r];
  }
  // move settings button
  if ([[[self contentView] subviews] count] > 0)
  {
    NSButton *setupButton = [[[self contentView] subviews] objectAtIndex:1];
    CGRect r;
    r = NSMakeRect(26.0, [self frame].size.height - 16.0,
                   20.0, 13.0);
    [setupButton setFrame:r];
  }
  // move refresh button
  if ([[[self contentView] subviews] count] > 0)
  {
    NSButton *refreshButton = [[[self contentView] subviews] objectAtIndex:2];
    CGRect r;
<<<<<<< HEAD
    r = NSMakeRect(49.0, [self frame].size.height - 16.0,
                   20.0, 13.0);
=======
    r = NSMakeRect(35.0, [self frame].size.height - 16.0, 
                   48.0, 13.0);
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
    [refreshButton setFrame:r];
  }
  // window background
  [self setBackgroundColor:[self sizedHUDBackground]];
  if (forceDisplay) 
  {
    [self display];
  }
}

- (void)setTitle:(NSString *)value 
{
  [super setTitle:value];
  [self windowDidResize:nil];
}

- (void)settingsWindow:(id)sender
{
  // settings
  wndSettings = [[frmSettingsController alloc] initWithWindowNibName:@"frmSettings"];      
  [[wndSettings window] makeKeyAndOrderFront:wndSettings];  
  [wndSettings showWindow:self];
}

- (void)refreshRSS:(id)sender
{
  [self initLogin];
}

- (void)addCloseWidget
{
  NSButton *closeButton = [[NSButton alloc] initWithFrame:NSMakeRect(3.0, [self frame].size.height - 16.0,
                                                                     20.0, 13.0)];
  [[self contentView] addSubview:closeButton];
  [closeButton setBezelStyle:NSRoundedBezelStyle];
  [closeButton setButtonType:NSMomentaryChangeButton];
  [closeButton setBordered:NO];
  [closeButton setImage:[NSImage imageNamed:@"hud_titlebar-close"]];
  [closeButton setTitle:@""];
  [closeButton setImagePosition:NSImageBelow];
  [closeButton setTarget:self];
  [closeButton setFocusRingType:NSFocusRingTypeNone];
  [closeButton setAction:@selector(orderOut:)];
  
  NSButton *setupButton = [[NSButton alloc] initWithFrame:NSMakeRect(26.0, [self frame].size.height - 16.0,
                                                                     20.0, 13.0)];
  [[self contentView] addSubview:setupButton];
  [setupButton setBezelStyle:NSRoundedBezelStyle];
  [setupButton setButtonType:NSMomentaryChangeButton];
  [setupButton setBordered:NO];
  [setupButton setImage:[NSImage imageNamed:@"settings"]];
  [setupButton setTitle:@""];
  [setupButton setImagePosition:NSImageBelow];
  [setupButton setTarget:self];
  [setupButton setFocusRingType:NSFocusRingTypeNone];
  [setupButton setAction:@selector(settingsWindow:)];
  
<<<<<<< HEAD
  NSButton *refreshButton = [[NSButton alloc] initWithFrame:NSMakeRect(49.0, [self frame].size.height - 16.0,
                                                                     20.0, 13.0)];
=======
  NSButton *refreshButton = [[NSButton alloc] initWithFrame:NSMakeRect(35.0, [self frame].size.height - 16.0, 
                                                                     48.0, 13.0)];
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
  [[self contentView] addSubview:refreshButton];
  [refreshButton setBezelStyle:NSRoundedBezelStyle];
  [refreshButton setButtonType:NSMomentaryChangeButton];
  [refreshButton setBordered:NO];
<<<<<<< HEAD
  [refreshButton setImage:[NSImage imageNamed:@"ref"]];
=======
  [refreshButton setImage:[NSImage imageNamed:@"refresh_rss"]];
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
  [refreshButton setTitle:@""];
  [refreshButton setImagePosition:NSImageBelow];
  [refreshButton setTarget:self];
  [refreshButton setFocusRingType:NSFocusRingTypeNone];
<<<<<<< HEAD
  [refreshButton setAction:@selector(refreshRSS:)];
=======
  [refreshButton setAction:@selector(refreshRSS:)];  
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
}

- (void)mouseDragged:(NSEvent *)theEvent
{
  
	if (shouldRedoInitials)
	{
		initialLocation = [theEvent locationInWindow];
		initialLocationOnScreen = [self convertBaseToScreen:[theEvent locationInWindow]];
		
		initialFrame = [self frame];
		shouldRedoInitials = NO;
		
		if (initialLocation.x > initialFrame.size.width - 20 && initialLocation.y < 20) 
    {
      [[NSCursor arrowCursor] set];
			shouldDrag = NO;
		}
		else 
    {
      [[NSCursor resizeLeftRightCursor] set];
			shouldDrag = YES;
		}
		
		screenFrame = [[NSScreen mainScreen] frame];
		windowFrame = [self frame];
		
		minY = windowFrame.origin.y+(windowFrame.size.height-288);
	}
	
	
	// 1. Is the Event a resize drag (test for bottom right-hand corner)?
	if (shouldDrag == FALSE)
	{
		currentLocation = [theEvent locationInWindow];
    // don't allow resize window height
    windowFrame.size.height = 70;
		windowFrame.size.width = initialFrame.size.width + (currentLocation.x - initialLocation.x);
		if (windowFrame.size.width < 400)
		{
			windowFrame.size.width = 400;
		}
		// iii. Set
		[self setFrame:windowFrame display:YES animate:NO];
	}
  else
	{
		//grab the current global mouse location; we could just as easily get the mouse location 
		//in the same way as we do in -mouseDown:
		currentLocation = [self convertBaseToScreen:[self mouseLocationOutsideOfEventStream]];
		newOrigin.x = currentLocation.x - initialLocation.x;
		newOrigin.y = currentLocation.y - initialLocation.y;
		// Don't let window get dragged up under the menu bar
		if( (newOrigin.y+windowFrame.size.height) > (screenFrame.origin.y+screenFrame.size.height) )
		{
			newOrigin.y=screenFrame.origin.y + (screenFrame.size.height-windowFrame.size.height);
		}
		//go ahead and move the window to the new location
		[self setFrameOrigin:newOrigin];
	}
}

- (void)mouseUp:(NSEvent *)theEvent
{
	shouldRedoInitials = YES;
}

- (bool)dragged
{
  return !shouldDrag;
}
@end
